<template>
  <a-modal v-model:open="open" :title="title" :confirm-loading="loading" @ok="handleOk">
    <a-form :wrapper-col="{span:18}" :label-col="{span:5}" :model="form" ref="formRef">
      <a-form-item label="名称" name="name" :rules="[{required: true, message: '请输入名称',trigger: 'blur'}]">
        <a-input placeholder="请输入名称" v-model:value="form.name" show-count :maxlength="8"/>
      </a-form-item>
      <form-item :col="[5,18]" label="标签颜色">
        <tag-select v-model:value="form.color"/>
      </form-item>
      <a-form-item label="排序" name="sort" help="数字越大越靠前，0~100 之间数字">
        <a-input-number placeholder="请输入排序" :min="0" :max="100" v-model:value="form.sort"/>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-switch v-model:checked="form.status" :checked-value="1" :un-checked-value="0"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {computed, reactive, ref, watch} from "vue";
import TagSelect from "@/components/TagSelect.vue";
import type {FormInstance} from "ant-design-vue";
import FormItem from "@/components/FormItem.vue";
import {useDictionaryStore} from "@/store/modules/dictionary.ts";

const open = defineModel('open', {default: false})
const { dataItem,current } = defineProps<{dataItem?: DictionaryType,current:{label:string, key: string}}>()
const title = computed(()=> dataItem?.id ? '编辑'+current.label : '新增'+current.label)
const loading = ref<boolean>(false)
const store = useDictionaryStore()
const formRef = ref<FormInstance>()
const form = reactive<DictionaryFormType>({
  id: 0,
  type: current.key,
  name: '',
  color:'',
  sort:0,
  status: 1
})
const handleOk = async () => {
  try {
    await formRef.value?.validate()
    const res = dataItem?.id
        ? await store.update(form)
        : await store.create(form)
    if (res) {
      open.value = false
      formRef.value?.resetFields()
    }
  } catch{
    return false
  } finally {
    setTimeout(() => loading.value = false, 3000)
  }
}
watch(()=>dataItem,()=>{
  if (dataItem?.id){
    Object.assign(form,dataItem)
  }else {
    Object.assign(form,{
      id: 0,
      name: '',
      type: current.key,
      color:'',
      sort:0,
      status: 1,
    })
  }
},{immediate: true})
</script>